import json
import random
import re

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django_redis import get_redis_connection

from verifications.libs.captcha.captcha import captcha
# Create your views here.
from django.views import View

from verifications.libs.yuntongxun.ccp_sms import CCP


class ImageCodeView(View):
    def get(self, request):
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')
        if not cur:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少参数'})
        text, image = captcha.generate_captcha()
        conn = get_redis_connection('imgsmscode')
        conn.setex(f'image_{cur}', 60, text)
        if pre:
            conn.delete(f'image_{pre}')
        return HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        mobile = data.get('mobile')
        id = data.get('id')
        text = data.get('text')
        if not all([mobile, id, text]):
            return JsonResponse({'code': 4103, 'errmsg': '缺少重要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 4103, 'errmsg': '手机号码错误'})
        if not re.match(r'^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$', id):
            return JsonResponse({'code': 4103, 'errmsg': 'uuid错误'})
        if not re.match(r'^[\da-zA-Z]{4}$', text):
            return JsonResponse({'code': 4103, 'errmsg': '验证码格式错误'})
        conn = get_redis_connection('imgsmscode')
        try:
            cur = conn.get(f'image_{id}').decode('utf-8')
        except Exception:
            return JsonResponse({'errno': 4103, 'errmsg': '没有图片验证码'})
        if not cur:
            return JsonResponse({'errno': 4002, 'errmsg': 'uuid错误'})
        if cur.lower() != text.lower():
            return JsonResponse({'errno': 4004, 'errmsg': '图片验证码错误'})
        sms_code = '%06d' % random.randint(0, 999999)

        sms_flag = conn.get(f'sms_flag_{mobile}')
        if not sms_flag:
            redis_conn_pip = conn.pipeline()
            redis_conn_pip.setex(f'sms_{mobile}', 300, sms_code)
            redis_conn_pip.setex(f'sms_flag_{mobile}', 60, 1)
            redis_conn_pip.execute()

            CCP().send_template_sms(mobile, [sms_code, 5], 1)

            print(sms_code)
        else:
            return JsonResponse({'errno': 4003,'errmsg': '发短信频繁'})

        return JsonResponse({'errno': 0,'errmsg': '短信发送成功'})
